#include "pack_metadata.h"

#include <QFile>
#include <QStringList>

#include <QJson/Parser>

PackMetadata::PackMetadata(const QString& filename, QObject* parent)
    : QObject(parent) {
  QFile f(filename);
  f.open(QFile::ReadOnly);
  QByteArray json = f.readAll();
  f.close();
  QJson::Parser parser;
  bool success = false;
  metadata_ = parser.parse(json, &success).toMap();
  Q_ASSERT(success);
}

QStringList PackMetadata::tilesheetPaths() const {
  QStringList ret;
  QVariantList tilesheets = metadata_.value("tilesheets").toList();
  foreach (QVariant variant, tilesheets) {
    QVariantMap tilesheet = variant.toMap();
    ret << tilesheet.value("name").toString();
  }
  return ret;
}

QSize PackMetadata::tilesheetSize(const QString& path) const {
  QVariantList tilesheets = metadata_.value("tilesheets").toList();
  foreach (QVariant variant, tilesheets) {
    QVariantMap tilesheet = variant.toMap();
    if (tilesheet.value("name").toString() == path) {
      int width = tilesheet.value("columns").toInt();
      int height = tilesheet.value("rows").toInt();
      return QSize(width, height);
    }
  }
  return QSize();
}

QStringList PackMetadata::tileNames(QString tilesheet_name) const {
  QStringList ret;
  QVariantList tilesheets = metadata_.value("tilesheets").toList();
  foreach (QVariant variant, tilesheets) {
    QVariantMap tilesheet = variant.toMap();
    if (tilesheet.value("name").toString() == tilesheet_name) {
      QVariantList tiles = tilesheet.value("tiles").toList();
      foreach (QVariant variant, tiles) {
        QVariantMap tile = variant.toMap();
        ret << tile.value("name").toString();
      }
    }
  }
  return ret;
}

QString PackMetadata::tileName(QString tilesheet_name, int index) const {
  QVariantList tilesheets = metadata_.value("tilesheets").toList();
  foreach (QVariant variant, tilesheets) {
    QVariantMap tilesheet = variant.toMap();
    if (tilesheet.value("name").toString() == tilesheet_name) {
      QVariantList tiles = tilesheet.value("tiles").toList();
      return tiles.at(index).toMap().value("name").toString();
    }
  }
  return QString();
}

QString PackMetadata::tileName(QString tilesheet_name, int row, int column) const {
  QVariantList tilesheets = metadata_.value("tilesheets").toList();
  foreach (QVariant variant, tilesheets) {
    QVariantMap tilesheet = variant.toMap();
    if (tilesheet.value("name").toString() == tilesheet_name) {
      QVariantList tiles = tilesheet.value("tiles").toList();
      foreach (QVariant variant, tiles) {
        QVariantMap tile = variant.toMap();
        if (tile.value("row").toInt() == row && tile.value("column").toInt() == column) {
          return tile.value("name").toString();
        }
      }
    }
  }
  return QString();
}

